﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.IO;
using CoolCode.Models;

namespace CoolCode.Web
{
    public static class HttpHandlerExtensions
    {
        private readonly static string[] viewMapping =  {
                    "~/Views/Master/{0}.aspx",
                    "~/Views/Buyer/{0}.aspx",
                    "~/Views/Vendor/{0}.aspx",
                    "~/Views/Home/{0}.aspx",
                    "~/WebServices/{0}.asmx",
                    "~/WebServices/{0}.ashx",
        };

        public static void View(this IHttpHandler httpHandler, string viewName)
        {
            string virtualPath = findViewPath(viewName);
            HttpContext.Current.Response.Redirect(virtualPath);
        }

        public static void View(this IHttpHandler httpHandler, string viewName, object param)
        {
            string queryString = param.ToQueryString();
            string virtualPath = string.Format("{0}?{1}", findViewPath(viewName), queryString);
            HttpContext.Current.Response.Redirect(virtualPath);
        }

        //HttpContext.Current.Response.Redirect(HttpContext.Current.Request.ApplicationPath);
        //public static void ViewError(this IContext context, string errorCode)
        //{
        //    string lngtyp = context.User != null ? context.User.LngType : string.Empty;
        //    string virtualPath = string.Format("~/Views/Home/Message.aspx?code={0}&lngtyp={1}", errorCode, lngtyp );
        //    HttpContext.Current.Response.Redirect(virtualPath); 
        //}


        public static void View<TView>(this IHttpHandler httpHandler)
        {
            HttpContext.Current.Response.Redirect(httpHandler.Url<TView>());
        }

        public static void View<TView>(this IHttpHandler httpHandler, object param)
        {
            HttpContext.Current.Response.Redirect(httpHandler.Url<TView>(param));
        }

        public static void ViewHome(this IHttpHandler httpHandler)
        {
            HttpContext.Current.Response.Redirect("~");
        }

        public static void ViewLogin(this IHttpHandler httpHandler)
        {
            ViewLogin(httpHandler, null);
        }

        public static void ViewLogin(this IHttpHandler httpHandler, string returnUrl)
        {
            string virtualPath = FormsAuthentication.LoginUrl;
            if (!string.IsNullOrEmpty(returnUrl))
                virtualPath += "?ReturnUrl=" + returnUrl;
            HttpContext.Current.Response.Redirect(virtualPath);
        }

        public static string Url(this IHttpHandler httpHandler, string viewName)
        {
            return findViewPath(viewName);
        }

        public static string Url(this IHttpHandler httpHandler, string viewName, object param)
        {
            string queryString = param.ToQueryString();
            string virtualPath = string.Format("{0}?{1}", httpHandler.Url(viewName), queryString);
            return virtualPath;
        }

        public static string Url(this IHttpHandler httpHandler)
        {
            return HttpContext.Current.Request.Url.PathAndQuery;
        }

        public static string Url<TView>(this IHttpHandler httpHandler)
        {
            string fullViewName = typeof(TView).FullName;
            string[] splits = fullViewName.Split('.');
            if (splits.Length < 2)
                throw new ArgumentException("Cannot find the namespace on view name");
            return string.Format("~/Views/{0}/{1}.aspx", splits[splits.Length - 2], splits[splits.Length - 1]);
        }

        public static string Url<TView>(this IHttpHandler httpHandler, object param)
        {
            string queryString = param.ToQueryString();
            string virtualPath = string.Format("{0}?{1}", httpHandler.Url<TView>(), queryString);
            return virtualPath;
        }

        private static string findViewPath(string viewName)
        {
            foreach (string mapping in viewMapping)
            {
                string virtualPath = string.Format(mapping, viewName);
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(virtualPath)))
                {
                    return virtualPath;
                }
            }
            throw new Exception("Cannot find the page: " + viewName);
        }

        public static void WriteFile(this IHttpHandler httpHandler, FileType fileType, string filePath)
        {
            string fileName = Path.GetFileName(filePath);
            HttpResponse Response = HttpContext.Current.Response;
            Response.Clear();
            Response.Buffer = true;
            //set Response charset as chinese
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

            //set content type as excel
            Response.ContentType = FileType.Excel.GetAttachedString();

            //this.EnableViewState = false;
            Response.WriteFile(filePath);
            Response.End();
        }

        public static void Warning(this IHttpHandler httpHandler, string message)
        {
            HttpResponse Response = HttpContext.Current.Response;
            Response.Write(string.Format("<h2 sytle='color:red;'>{0}</h2>", Utility.HtmlEncode(message)));
        }

        public static ILog BuildLog(this IHttpHandler httpHandler, UserAction action, string message)
        {
            var Digger = CoolCode.Ioc.InjectTable.GetDigger();
            ILog log = Digger.Dig<ILog>();
            if (log == null) return null;

            log.Path = RequestUtility.GetUrl();
            log.User = HttpContext.Current.User.Identity.Name;
            log.Time = DateTime.Now;
            log.Type = action.GetAttachedString();
            log.Desc = message;
            log.From = RequestUtility.GetIP();
            log.Name = RequestUtility.GetPageName();

            return log;
        }
    }

    public enum FileType
    {
        [AttachString("application/ms-excel")]
        Excel,
    }

}
